<template>
	<div class="confirmOrder">
		<!-- 头部 -->
		<div class="confirmOrder-header">
			<div class="header-content">
				<p>
					<i class="el-icon-s-order"></i>
				</p>
				<p>确认订单</p>
				<router-link to></router-link>
			</div>
		</div>
		<!-- 头部END -->

		<!-- 主要内容容器 -->
		<div class="content">
			<!-- 选择地址 -->
			<div class="section-address">
				<p class="title">收货地址</p>
				<div class="address-body">
					<ul>
						<li v-if="addressList.length != 0" style="cursor: pointer;" @click="confirmAddress = index" :class="index == confirmAddress ? 'in-section' : ''"
						 v-for="(item,index) in addressList" :key="item.id">
							<h2>{{item.receiverName}}</h2>
							<p class="phone">{{item.receiverPhone}}</p>
							<p class="address">{{item.receiverDetailAddr}}</p>
						</li>
						<li style="cursor: pointer;" class="add-address" @click="addAddr()">
							<i class="el-icon-circle-plus-outline"></i>
							<p>添加新地址</p>
						</li>
					</ul>
				</div>
			</div>
			<!-- 选择地址END -->

			<!-- 商品及优惠券 -->
			<div class="section-goods">
				<p class="title">商品及优惠券</p>
				<div class="goods-list">
					<ul>
						<li v-for="item in orderDetail.orderItems" :key="item.productId">
							<img :src="item.productImage" />
							<span class="pro-name">{{item.productName}}</span>
							<span class="pro-price">{{item.price}}元 x {{item.count}}</span>
							<span class="pro-status"></span>
							<span class="pro-total">{{(item.count * item.price).toFixed(2)}}元</span>
						</li>
					</ul>
				</div>
			</div>
			<!-- 商品及优惠券END -->

			<!-- 配送方式 -->
			<div class="section-shipment">
				<p class="title">配送方式</p>
				<p class="shipment">包邮</p>
			</div>
			<!-- 配送方式END -->

			<!-- 发票 -->
			<div class="section-invoice">
				<p class="title">发票</p>
				<p class="invoice">电子发票</p>
				<p class="invoice">个人</p>
				<p class="invoice">商品明细</p>
			</div>
			<!-- 发票END -->

			<!-- 结算列表 -->
			<div class="section-count">
				<div class="money-box">
					<ul>
						<li>
							<span class="title">商品件数：</span>
							<span class="value">{{getNum}}件</span>
						</li>
						<li>
							<span class="title">商品总价：</span>
							<span class="value">{{orderDetail.payAmount}}元</span>
						</li>
						<li>
							<span class="title">活动优惠：</span>
							<span class="value">-0元</span>
						</li>
						<li>
							<span class="title">优惠券抵扣：</span>
							<span class="value">-0元</span>
						</li>
						<li>
							<span class="title">运费：</span>
							<span class="value">0元</span>
						</li>
						<li class="total">
							<span class="title">应付总额：</span>
							<span class="value">
								<span class="total-price">{{orderDetail.payAmount}}</span>元
							</span>
						</li>
					</ul>
				</div>
			</div>
			<!-- 结算列表END -->

			<!-- 结算导航 -->
			<div class="section-bar">
				<div class="btn">
					<router-link to="/cart" class="btn-base btn-return">返回购物车</router-link>
					<a href="javascript:void(0);" @click="addOrder" class="btn-base btn-primary">确认</a>
				</div>
			</div>
			<!-- 结算导航END -->
		</div>
		<!-- 主要内容容器END -->

		<!-- 添加弹窗 -->
		<el-dialog title="添加" :visible.sync="addAddressDialog">
			<address-add @closeAddressDialog="closeAddressDialog" @refreshDataList="refreshAddress" />
		</el-dialog>

		<!-- 修改弹窗 -->
		<!-- 		<el-dialog title="修改" :visible.sync="updateAdressDialog">
			<address-update :emitAddressData="emitAddressData" @closeUpdateAddressDialog="closeUpdateAddressDialog" @onSubmit="onSubmit" />
		</el-dialog> -->

	</div>
</template>

<script>
	import AddressAdd from "./address-add";
	// import AddressUpdate from './address-update'

	import addressAPI from '../api/address.js'
	import cartItemAPI from 'api/cartItem.js';
	import orderAPI from '../api/order.js'
	import productAPI from '../api/product.js'
	
	import {
		mapGetters
	} from "vuex";
	import {
		mapActions
	} from "vuex";

	export default {
		name: "ConfirmOrder",

		components: {
			AddressAdd
		},

		activated() {
			console.log("activated");
			console.log('route', this.$route);
			if (this.$route.query.hasOwnProperty("orderItems") && this.$route.query.hasOwnProperty("fromCart")) {
				this.orderDetail = this.$route.query;
				this.getUserAddress();
			} else {
				this.notifyError("请购买商品，再下单");
				this.$router.push("/goods");
			}
		},

		data() {
			return {
				userInfo: this.$store.getters.getUser,
				addAddressDialog: false, //添加地址对话框
				updateAdressDialog: false, //更新地址对话框

				// 虚拟数据
				confirmAddress: 0, // 选择的地址id

				// 上一页传过来的数据
				orderDetail: {
					orderItems: [],
					payAmount: null,
					fromCart: null
				},

				// 提交订单的数据
				orderItems: [],

				// 地址列表
				addressList: [],


			};
		},

		computed: {
			// 结算的商品数量; 结算商品总计; 结算商品信息
			...mapGetters(["getUser", "getNum"]),
			payAmount() {
				var totalPrice = 0
				this.orderItems.forEach(item => {
					totalPrice = totalPrice + (item.count * item.price)
				})
			}
		},

		deactivated() {
			this.orderDetail={}
			this.orderItems=[]
		},

		methods: {
			...mapActions(["setShoppingCart"]),
			
			// 拿到用户地址列表
			async getUserAddress() {
				var res = await addressAPI.getAddressById(this.userInfo.userId)
				this.addressList = res.list
			},

			// 点击下单
			async addOrder() {
				var that = this
				let i = 0
				// 删除购物车数据，删除库存
				for( i=0;i<this.orderDetail.orderItems.length;i++) {
					var item = this.orderDetail.orderItems[i]
					
					if(this.orderDetail.fromCart == "true"){ // 删购物车，删库存
						var res = await cartItemAPI.toOrder({
								count: item.count,
								memberId: that.userInfo.userId,
								productId: item.productId
						})
						if(res.msg == "库存充足"){
							that.orderItems.push(item)
						}else{
							that.notifyError(res.msg)
						}
					}else{ // 删库存
						var res = await productAPI.toOrder({
							count: item.count,
							productId: item.productId
						})
						if(res.msg == "库存充足"){
							that.orderItems.push(item)
						}else{
							that.notifyError(res.msg)
						}
					}	
				}
				
				if (i == that.orderDetail.orderItems.length) {
					if(that.orderItems.length != 0){
						that.createOrder()
					}else{
						that.$router.push("/goods")
					}
				}
			},
			
			createOrder() {
				var that  = this
				var address = that.addressList[that.confirmAddress]
				// 下单了
				orderAPI.createOrder({
					"memberId": that.userInfo.userId,
					"memberUsername": that.userInfo.userName,
					"orderItems": that.orderItems,
					"payAmount": that.payAmount,
					"receiverDetailAddr": address.receiverDetailAddr,
					"receiverName": address.receiverName,
					"receiverPhone": address.receiverPhone
				}).then(res => {
					if(this.orderDetail.fromCart == "true"){
						that.updateCart() // 从购物车过来，更新购物车
					}else {
						that.$router.replace("/order")
						that.notifySucceed('下单成功！')
					}
				})
			},
			
			updateCart() {
				var that = this
				// 更新购物车
				cartItemAPI.getCartItemList(that.userInfo.userId).then(res => {
					var itemList = []
					res.data.forEach((item, index) => {
						var price = item.itemTotalPrice / item.count
						itemList.push(
							Object.assign({}, item, {
								'price': price,
								'check': true
							})
						)
					})
					that.setShoppingCart(itemList);
					// 跳转到支付页面
					that.$router.replace("/order")
					that.notifySucceed('下单成功！')
				})
			},
			
			addAddr() {
				console.log("add address!");
				this.addAddressDialog = true;
			},
			closeAddressDialog() {
				this.addAddressDialog = false;
			},
			refreshAddress() {
				this.getUserAddress()
			}
		}
	};
</script>

<style scoped>
	.confirmOrder {
		background-color: #f5f5f5;
		padding-bottom: 20px;
	}

	/* 头部CSS */
	.confirmOrder .confirmOrder-header {
		background-color: #fff;
		border-bottom: 2px solid #ff6700;
		margin-bottom: 20px;
	}

	.confirmOrder .confirmOrder-header .header-content {
		width: 1225px;
		margin: 0 auto;
		height: 80px;
	}

	.confirmOrder .confirmOrder-header .header-content p {
		float: left;
		font-size: 28px;
		line-height: 80px;
		color: #424242;
		margin-right: 20px;
	}

	.confirmOrder .confirmOrder-header .header-content p i {
		font-size: 45px;
		color: #ff6700;
		line-height: 80px;
	}

	/* 头部CSS END */

	/* 主要内容容器CSS */
	.confirmOrder .content {
		width: 1225px;
		margin: 0 auto;
		padding: 48px 0 0;
		background-color: #fff;
	}

	/* 选择地址CSS */
	.confirmOrder .content .section-address {
		margin: 0 48px;
		overflow: hidden;
	}

	.confirmOrder .content .section-address .title {
		color: #333;
		font-size: 18px;
		line-height: 20px;
		margin-bottom: 20px;
	}

	.confirmOrder .content .address-body li {
		float: left;
		color: #333;
		width: 220px;
		height: 178px;
		border: 1px solid #e0e0e0;
		padding: 15px 24px 0;
		margin-right: 17px;
		margin-bottom: 24px;
	}

	.confirmOrder .content .address-body .in-section {
		border: 1px solid #ff6700;
	}

	.confirmOrder .content .address-body li h2 {
		font-size: 18px;
		font-weight: normal;
		line-height: 30px;
		margin-bottom: 10px;
	}

	.confirmOrder .content .address-body li p {
		font-size: 14px;
		color: #757575;
	}

	.confirmOrder .content .address-body li .address {
		padding: 10px 0;
		max-width: 180px;
		max-height: 88px;
		line-height: 22px;
		overflow: hidden;
	}

	.confirmOrder .content .address-body .add-address {
		text-align: center;
		line-height: 30px;
	}

	.confirmOrder .content .address-body .add-address i {
		font-size: 30px;
		padding-top: 50px;
		text-align: center;
	}

	/* 选择地址CSS END */

	/* 商品及优惠券CSS */
	.confirmOrder .content .section-goods {
		margin: 0 48px;
	}

	.confirmOrder .content .section-goods p.title {
		color: #333;
		font-size: 18px;
		line-height: 40px;
	}

	.confirmOrder .content .section-goods .goods-list {
		padding: 5px 0;
		border-top: 1px solid #e0e0e0;
		border-bottom: 1px solid #e0e0e0;
	}

	.confirmOrder .content .section-goods .goods-list li {
		padding: 10px 0;
		color: #424242;
		overflow: hidden;
	}

	.confirmOrder .content .section-goods .goods-list li img {
		float: left;
		width: 30px;
		height: 30px;
		margin-right: 10px;
	}

	.confirmOrder .content .section-goods .goods-list li .pro-name {
		float: left;
		width: 650px;
		line-height: 30px;
	}

	.confirmOrder .content .section-goods .goods-list li .pro-price {
		float: left;
		width: 150px;
		text-align: center;
		line-height: 30px;
	}

	.confirmOrder .content .section-goods .goods-list li .pro-status {
		float: left;
		width: 99px;
		height: 30px;
		text-align: center;
		line-height: 30px;
	}

	.confirmOrder .content .section-goods .goods-list li .pro-total {
		float: left;
		width: 190px;
		text-align: center;
		color: #ff6700;
		line-height: 30px;
	}

	/* 商品及优惠券CSS END */

	/* 配送方式CSS */
	.confirmOrder .content .section-shipment {
		margin: 0 48px;
		padding: 25px 0;
		border-bottom: 1px solid #e0e0e0;
		overflow: hidden;
	}

	.confirmOrder .content .section-shipment .title {
		float: left;
		width: 150px;
		color: #333;
		font-size: 18px;
		line-height: 38px;
	}

	.confirmOrder .content .section-shipment .shipment {
		float: left;
		line-height: 38px;
		font-size: 14px;
		color: #ff6700;
	}

	/* 配送方式CSS END */

	/* 发票CSS */
	.confirmOrder .content .section-invoice {
		margin: 0 48px;
		padding: 25px 0;
		border-bottom: 1px solid #e0e0e0;
		overflow: hidden;
	}

	.confirmOrder .content .section-invoice .title {
		float: left;
		width: 150px;
		color: #333;
		font-size: 18px;
		line-height: 38px;
	}

	.confirmOrder .content .section-invoice .invoice {
		float: left;
		line-height: 38px;
		font-size: 14px;
		margin-right: 20px;
		color: #ff6700;
	}

	/* 发票CSS END */

	/* 结算列表CSS */
	.confirmOrder .content .section-count {
		margin: 0 48px;
		padding: 20px 0;
		overflow: hidden;
	}

	.confirmOrder .content .section-count .money-box {
		float: right;
		text-align: right;
	}

	.confirmOrder .content .section-count .money-box .title {
		float: left;
		width: 126px;
		height: 30px;
		display: block;
		line-height: 30px;
		color: #757575;
	}

	.confirmOrder .content .section-count .money-box .value {
		float: left;
		min-width: 105px;
		height: 30px;
		display: block;
		line-height: 30px;
		color: #ff6700;
	}

	.confirmOrder .content .section-count .money-box .total .title {
		padding-top: 15px;
	}

	.confirmOrder .content .section-count .money-box .total .value {
		padding-top: 10px;
	}

	.confirmOrder .content .section-count .money-box .total-price {
		font-size: 30px;
	}

	/* 结算列表CSS END */

	/* 结算导航CSS */
	.confirmOrder .content .section-bar {
		padding: 20px 48px;
		border-top: 2px solid #f5f5f5;
		overflow: hidden;
	}

	.confirmOrder .content .section-bar .btn {
		float: right;
	}

	.confirmOrder .content .section-bar .btn .btn-base {
		float: left;
		margin-left: 30px;
		width: 158px;
		height: 38px;
		border: 1px solid #b0b0b0;
		font-size: 14px;
		line-height: 38px;
		text-align: center;
	}

	.confirmOrder .content .section-bar .btn .btn-return {
		color: rgba(0, 0, 0, 0.27);
		border-color: rgba(0, 0, 0, 0.27);
	}

	.confirmOrder .content .section-bar .btn .btn-primary {
		background: #ff6700;
		border-color: #ff6700;
		color: #fff;
	}

	/* 结算导航CSS */

	/* 主要内容容器CSS END */
</style>
